package com.shire.shire_interface.controller.massmsg;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.bin.Response;
import com.shire.shire_interface.common.utils.DateUtil;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.model.friend.WxFriendExample;
import com.shire.shire_interface.model.group.WxGroupExample;
import com.shire.shire_interface.model.massmsg.WxMassMsgItem;
import com.shire.shire_interface.model.massmsg.WxMassMsgItemExample;
import com.shire.shire_interface.model.massmsg.WxMassMsgTask;
import com.shire.shire_interface.model.massmsg.WxMassMsgTaskExample;
import com.shire.shire_interface.service.friend.WxFriendService;
import com.shire.shire_interface.service.group.WxGroupService;
import com.shire.shire_interface.service.massmsg.WxMassMsgItemService;
import com.shire.shire_interface.service.massmsg.WxMassMsgTaskService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


//@Api(tags = "群发")
@RestController
@RequestMapping("/msg")
public class WxMassMsgTaskController extends BaseController {

    @Resource
    private WxMassMsgTaskService wxMassMsgTaskService;
    @Resource
    private WxMassMsgItemService wxMassMsgItemService;
    @Resource
    private WxGroupService wxGroupService;
    @Resource
    private WxFriendService wxFriendService;

//    @ApiOperation(value = "发送csId, wxAccount,groupIds, msg, type, batchInterval, batchSize")
    @ResponseBody
    @PostMapping("/insetMsgTask")
    public Response insetGroupMsgTask(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        try {
            Integer csId = jsonObject.getInteger("csId");
            String wxAccount = jsonObject.getString("wxAccount");
            JSONArray groupIds = jsonObject.getJSONArray("groupIds");
            String msg = jsonObject.getString("msg");
            Integer type = jsonObject.getInteger("msgtype");
            Integer batchInterval = jsonObject.getInteger("batchInterval");
            Integer batchSize = jsonObject.getInteger("batchSize");
            String msgExtra = jsonObject.getString("msgExtra");

            String sendTime = jsonObject.getString("sendTime");

            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            if (!jsonObject.containsKey("sendTime")) {
                WxMassMsgTask wxMassMsgTask = new WxMassMsgTask();
                wxMassMsgTask.setCsid(csId);
                wxMassMsgTask.setTaskcount(groupIds.size());
                wxMassMsgTask.setMsgtype(type);
                wxMassMsgTask.setMsgcontent(msg);
                wxMassMsgTask.setMsgextra(msgExtra);
                wxMassMsgTask.setBatchsize(batchSize);
                wxMassMsgTask.setBatchinterval(batchInterval);
                wxMassMsgTask.setSendtime(DateUtil.String2Date(sendTime));
                wxMassMsgTask.setCreatetime(new Date());
                wxMassMsgTaskService.insetGroupMsgTask(wxMassMsgTask);
                insertMassMsgSubTask(csId, groupIds, wxMassMsgTask);
            }else if (jsonObject.getString("sendTime").startsWith("[")){
                JSONArray sendTimeArr = jsonObject.getJSONArray("sendTime");
                for (Object st : sendTimeArr){
                    String time = (String) st;
                    WxMassMsgTask wxMassMsgTask = new WxMassMsgTask();
                    wxMassMsgTask.setCsid(csId);
                    wxMassMsgTask.setTaskcount(groupIds.size());
                    wxMassMsgTask.setMsgtype(type);
                    wxMassMsgTask.setMsgcontent(msg);
                    wxMassMsgTask.setMsgextra(msgExtra);
                    wxMassMsgTask.setBatchsize(batchSize);
                    wxMassMsgTask.setBatchinterval(batchInterval);
                    wxMassMsgTask.setSendtime(DateUtil.String2Date(time));
                    wxMassMsgTask.setCreatetime(new Date());
                    wxMassMsgTaskService.insetGroupMsgTask(wxMassMsgTask);
                    insertMassMsgSubTask(csId, groupIds, wxMassMsgTask);
                }

            }
            response.success("成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.error("失败");
        }
        return response;
    }

    private void insertMassMsgSubTask(Integer csId, JSONArray groupIds, WxMassMsgTask wxMassMsgTask) {
        for (Object groupId : groupIds) {
            JSONObject itemObj = (JSONObject) groupId;
            WxMassMsgItem wxMassMsgItem = new WxMassMsgItem();
            wxMassMsgItem.setTaskid(wxMassMsgTask.getId());
            wxMassMsgItem.setCsid(csId);
            wxMassMsgItem.setFromaccount(itemObj.getString("fromAccount"));
            wxMassMsgItem.setToaccount(itemObj.getString("toAccount"));
            wxMassMsgItem.setToaccounttype(itemObj.getString("toAccount").endsWith("@chatroom") ? 1 : 0);

            wxMassMsgItemService.insert(wxMassMsgItem);
        }
    }

    //    @ApiOperation(value = "列表 csId,")
    @ResponseBody
    @PostMapping("/msgTaskList")
    public Response getMassMsgTaskHistory(@RequestBody JSONObject jsonObject,HttpSession session){
        Response response = new Response();
        try {
            Integer csId = jsonObject.getInteger("csId");

            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            WxMassMsgTaskExample example = new WxMassMsgTaskExample();
            example.createCriteria().andCsidEqualTo(csId);
            example.setOrderByClause("createTime desc");

            addPageParamToExample(jsonObject,example);

            List<WxMassMsgTask> massMsgTaskHistory = wxMassMsgTaskService.getMassMsgTaskHistory(example);
            response.setData(massMsgTaskHistory);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

//    @ApiOperation(value = "发送账号列表 taskId")
    @ResponseBody
    @PostMapping("/sentAccount")
    public Response sentAccount(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        if (!checkLoginUser(session)){
            response.error("请登录！");
            response.setCode(501);
            return response;
        }

        Integer taskId = jsonObject.getInteger("taskId");
//        wxMassMsgItemService.selectByPrimaryKey(taskId);


        return response;
    }

//    @ApiOperation(value = "取得任务明细 taskId")
    @ResponseBody
    @PostMapping("/listTaskDetail")
    public Response listTaskDetail(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        try {

            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            Integer taskId = jsonObject.getInteger("taskId");
            WxMassMsgItemExample itemExample = new WxMassMsgItemExample();
            itemExample.createCriteria().andTaskidEqualTo(taskId);

            WxMassMsgTask task = wxMassMsgTaskService.selectByPrimaryKey(taskId);

            List<WxMassMsgItem> msgItems = wxMassMsgItemService.selectByExample(itemExample);

            List<String> friendIds = new ArrayList<>();
            List<String> groupIds = new ArrayList<>();
            List<Object> objectList = new ArrayList<>();

            for (WxMassMsgItem msgItem : msgItems) {
                if (msgItem.getToaccount().endsWith("@chatroom")){
                    groupIds.add(msgItem.getToaccount());
                }else {
                    friendIds.add(msgItem.getToaccount());
                }
            }

            JSONObject retJson = new JSONObject();

            retJson.put("items", msgItems);
            if (groupIds.size()>0){
                WxGroupExample groupExample = new WxGroupExample();
                groupExample.createCriteria().andCsidEqualTo(task.getCsid()).andGroupnoIn(groupIds);
                retJson.put("groups", wxGroupService.selectByExample(groupExample));
            }
            if (friendIds.size()>0){
                WxFriendExample friendExample = new WxFriendExample();
                friendExample.createCriteria().andCsidEqualTo(task.getCsid()).andFriendwxidIn(friendIds);
                retJson.put("friends", wxFriendService.selectByExample(friendExample));
            }
            response.setData(retJson);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

//    @ApiOperation(value = "取消 taskId")
    @ResponseBody
    @PostMapping("/cancel")
    public Response cancel(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            Integer taskId = jsonObject.getInteger("taskId");
            WxMassMsgTask wxMassMsgTask = wxMassMsgTaskService.selectByPrimaryKey(taskId);
            wxMassMsgTask.setStatus(2);
            wxMassMsgTaskService.updateByPrimaryKey(wxMassMsgTask);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

//    @ApiOperation(value = "删除 taskId")
    @ResponseBody
    @PostMapping("/del")
    public Response del(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            Integer taskId = jsonObject.getInteger("taskId");
            wxMassMsgTaskService.deleteByPrimaryKey(taskId);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

//    @ApiOperation(value = "更新消息taskId, msg")
    @ResponseBody
    @PostMapping("/updateMsg")
    public Response updateMsg(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            Integer taskId = jsonObject.getInteger("taskId");
            String msg = jsonObject.getString("msg");
            WxMassMsgTask wxMassMsgTask = wxMassMsgTaskService.selectByPrimaryKey(taskId);
            wxMassMsgTask.setMsgcontent(msg);
            wxMassMsgTaskService.updateByPrimaryKey(wxMassMsgTask);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }
}
